package com.ssi.mrms.action;

import static com.opensymphony.xwork2.Action.SUCCESS;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionContext;
import com.ssi.mrms.model.User;
import com.ssi.mrms.service.UserService;
import com.ssi.mrms.utils.SecurityUtils;

@Action(value = "/login", results = { @Result(name = "success", location = "login.jsp") })
@Namespaces(value = { @Namespace("/") })
public class LoginAction extends BaseAction {

	private static final Logger logger = Logger.getLogger(LoginAction.class);
	private UserService userService = lookupBean(UserService.class, "UserService");
	
	public static String READ_WRITE = "RW";
	public static String READ_ONLY = "RO";
	public static String NO_PRIVILEDGE = "N";

	public String execute() throws Exception {
		logger.info("LoginAction Home.");
		return SUCCESS;
	}


	@Action(value = "/loginSuccess", results = { @Result(name = "success", location = "/home/index", type = "redirect") })
	public String loginSuccess() throws Exception {
		logger.info("LoginAction loginSuccess.");
		init();
		return SUCCESS;
	}

	@Action(value = "/logoutSuccess", results = { @Result(name = "success", location = "/login", type = "redirect") })
	public String logoutSuccess() throws Exception {
		logger.info("LoginAction logoutSuccess.");
//		init();
		return SUCCESS;
	}

	private void init() {
		
		if (StringUtils.isNotEmpty(SecurityUtils.getUsername())) {
			
			User user = userService.findByUsername(SecurityUtils.getUsername());
			logger.info("User : " + ToStringBuilder.reflectionToString(user));
			logger.info("Role : " + ToStringBuilder.reflectionToString(user.getUserRole()));
			ActionContext.getContext().getSession().put("objUser", user);
			ActionContext.getContext().getSession().put("objUserRole", user.getUserRole());
			
			String userGrant = user.getUserRole().getUserGrant();
			String roomGrant = user.getUserRole().getUserGrant();
			String resGrant = user.getUserRole().getUserGrant();
			
			ActionContext.getContext().getSession().put("isUserRW", READ_WRITE.equals(userGrant));
			ActionContext.getContext().getSession().put("isUserRO", READ_ONLY.equals(userGrant));
			ActionContext.getContext().getSession().put("isRoomRW", READ_WRITE.equals(roomGrant));
			ActionContext.getContext().getSession().put("isRoomRO", READ_ONLY.equals(roomGrant));
			ActionContext.getContext().getSession().put("isResidentRW", READ_WRITE.equals(resGrant));
			ActionContext.getContext().getSession().put("isResidentRO", READ_ONLY.equals(resGrant));
			
		}else{
//			logoutSuccess();
		}
	}

}
